import axios, { type AxiosInstance, type AxiosResponse } from 'axios'
import type { ApiResponse, RequestConfig } from '@/types/http'
import { message } from 'ant-design-vue'
import { STORAGE_LOGIN_TOKEN } from '@/constants/localKey'
import { useLoadingStore } from '@/stores/modules/loading'

// 创建axios实例
const instance: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json',
    },
})

// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        // 从本地存储获取token
        const token = localStorage.getItem(STORAGE_LOGIN_TOKEN)
        if (token && config.headers) {
            config.headers.Authorization = `Bearer ${token}`
        }

        // 增加请求计数
        try {
            const loadingStore = useLoadingStore()
            loadingStore.addPendingRequest()
        } catch (error) {
            // Pinia 未初始化时忽略错误
            console.warn('Loading store not available:', error)
        }

        return config
    },
    (error) => {
        console.error('请求拦截器错误:', error)
        // 请求失败时也要减少计数
        try {
            const loadingStore = useLoadingStore()
            loadingStore.removePendingRequest()
        } catch (storeError) {
            // Pinia 未初始化时忽略错误
            console.warn('Loading store not available:', storeError)
        }
        return Promise.reject(error)
    },
)

// 响应拦截器 - 只在拦截器中处理UI提示，不处理错误抛出
instance.interceptors.response.use(
    (response: AxiosResponse) => {
        // 减少请求计数
        try {
            const loadingStore = useLoadingStore()
            loadingStore.removePendingRequest()
        } catch (error) {
            // Pinia 未初始化时忽略错误
            console.warn('Loading store not available:', error)
        }

        if (response.data.code === 200) {
            return response.data
        }
        return Promise.reject(response.data)
    },
    (error) => {
        console.error('响应拦截器错误:', error)

        // 减少请求计数
        try {
            const loadingStore = useLoadingStore()
            loadingStore.removePendingRequest()
        } catch (storeError) {
            // Pinia 未初始化时忽略错误
            console.warn('Loading store not available:', storeError)
        }

        // 处理UI提示
        if (error.response) {
            const { status, data } = error.response

            switch (status) {
                case 401:
                    message.error('未授权，请重新登录')
                    localStorage.removeItem(STORAGE_LOGIN_TOKEN)
                    window.location.href = '/login'
                    break
                case 403:
                    message.error('拒绝访问')
                    break
                case 404:
                    message.error('请求的资源不存在')
                    break
                case 500:
                    message.error('服务器内部错误')
                    break
                default:
                    message.error(data?.message || '请求失败')
                    break
            }
        } else if (error.request) {
            message.error('网络错误，请检查网络连接')
        } else {
            message.error('请求配置错误')
        }
    },
)

// 导出axios实例
export default instance

// 便捷方法
export const request = {
    get: <T = unknown>(url: string, config?: RequestConfig) => instance.get<ApiResponse<T>>(url, config),

    post: <T = unknown>(url: string, data?: T, config?: RequestConfig) =>
        instance.post<ApiResponse<T>>(url, data, config),

    put: <T = unknown>(url: string, data?: T, config?: RequestConfig) =>
        instance.put<ApiResponse<T>>(url, data, config),

    delete: <T = unknown>(url: string, config?: RequestConfig) => instance.delete<ApiResponse<T>>(url, config),

    patch: <T = unknown>(url: string, data?: T, config?: RequestConfig) =>
        instance.patch<ApiResponse<T>>(url, data, config),
}
